package com.daervin.svc.parser.hot;

import com.daervin.svc.common.constants.Constants;
import com.daervin.svc.common.dto.hot.BilibiliHotData;
import com.daervin.svc.common.dto.hot.BilibiliHotList;
import com.daervin.svc.common.dto.hot.BilibiliHotResult;
import com.daervin.svc.dal.model.HotItem;
import com.daervin.svc.parser.RootParser;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Json;

import java.util.ArrayList;
import java.util.List;

import static com.daervin.svc.common.constants.HotSiteEnum.BILI_BILI;

/**
 * @author daervin
 * @version 1.0.0
 * @since 1.0.0
 */
public class BiliBiliParser extends RootParser {

    private final static Logger LOGGER = Logger.getLogger(BiliBiliParser.class);

    public BiliBiliParser(String url) {
        super(url);
    }

    @Override
    public void listProcess(Page page) {
        Json responseJson = page.getJson();
        if (responseJson == null) {
            return;
        }
        BilibiliHotResult response = responseJson.toObject(BilibiliHotResult.class);
        if (response == null || CollectionUtils.isEmpty(response.getData()) || response.getData().get(0) == null) {
            return;
        }
        BilibiliHotData hotData = response.getData().get(0);
        if (hotData == null || CollectionUtils.isEmpty(hotData.getList())) {
            return;
        }
        List<HotItem> hotItemList = new ArrayList<>();
        for (BilibiliHotList item : hotData.getList()) {
            hotItemList.add(new HotItem(BILI_BILI.ID, item.getTitle(), "https://www.bilibili.com/video/" + item.getBvid(), item.getScore()));
        }
        if (CollectionUtils.isEmpty(hotItemList)) {
            return;
        }
        page.putField(Constants.PARSER_RESULT, hotItemList);
    }
}
